﻿using AppTemplate.UI.Sys;
using AppTemplate.UI.ViewModels;
using AppTemplate.UI.Views;
using Microsoft.Extensions.Configuration;
using Serilog;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Windows;

namespace AppTemplate.UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            try
            {
                //初始化异常处理
                this.DispatcherUnhandledException += HandleAppException;



                //初始化配置
                IConfiguration configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .Build();

                //初始化日志
                Log.Logger = new LoggerConfiguration()
                 .ReadFrom.Configuration(configuration)
                 .Enrich.FromLogContext()
                 .CreateLogger();

                //初始化依赖注入
                DI.Init(configuration);

                //初始化应用
                AppState.Init(configuration);

            }
            catch (Exception ex)
            {
                var details = System.Text.Encoding.Default.GetBytes(ex.StackTrace ?? string.Empty);
                EventLog.WriteEntry("AppTemplate", ex.Message, EventLogEntryType.Error, 0, 1, details);
                MessageBox.Show("系统启动异常,请查看Window日志", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown();
            }
        }

        private void HandleAppException(object sender, global::System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string msg = e.Exception.InnerException?.Message == null ? e.Exception.Message : e.Exception.InnerException.Message;
            Log.Error(e.Exception, msg);
            MessageBox.Show(this.MainWindow, msg, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            e.Handled = true;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            AppState.Instance.Go<LoginView>("登录");
        }
    }
}
